<template>
  <detail title="">
    <div class="ConsultResult" style="width: 100%">
      <template>
        <div
          class="flex-align"
          v-if="
            (addtype !== 'record' &&
              mode === 'edit' &&
              !detail.itemRulesDTOList.length) ||
            (addtype !== 'record' && detail.itemRulesDTOList.length)
          "
        >
          <p class="title">处置规则</p>
          <div
            class="add-row"
            @click="dealArray(detail.itemRulesDTOList)"
            v-if="mode === 'edit' && addtype !== 'record'"
          >
            + 添加处置部门
          </div>
        </div>
        <c-table
          v-if="
            (addtype !== 'record' &&
              mode === 'edit' &&
              !detail.itemRulesDTOList.length) ||
            (addtype !== 'record' && detail.itemRulesDTOList.length)
          "
          :data="detail.itemRulesDTOList || []"
          style="width: 100%"
        >
          <c-table-column prop="dept" label="处置部门">
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">{{
                scope.row.unitName || '--'
              }}</template>
              <template v-else>
                <c-cascader
                  filterable
                  :class="{
                    err: !scope.row.unitName && scope.row.isValidate
                  }"
                  :show-all-levels="false"
                  placeholder="请选择处置部门"
                  :options="deptTreeData"
                  :props="treeProps"
                  v-model="scope.row.unitCode"
                  @change="
                    (val) => handleTreeSelectChange(scope.row, val, 'unitName')
                  "
                >
                </c-cascader>
                <!-- <c-select :class="{
                  err: !scope.row.unitCode && scope.row.isValidate
                }" @change="changeDept(scope.row, optionsDept, scope.row.unitCode)" v-model="scope.row.unitCode" placeholder="请选择协同部门">
                  <c-option
                    v-for="item in optionsDept"
                    :disabled="item.disabled"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </c-option>
                </c-select> -->
              </template>
            </template>
          </c-table-column>
          <c-table-column prop="user" label="角色">
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">{{
                arrFind(optionsUser, scope.row.roleCode) || '--'
              }}</template>
              <template v-else>
                <!-- 此处为普通下拉选择 -->
                <c-select
                  :class="{
                    err: !scope.row.roleCode && scope.row.isValidate
                  }"
                  @change="
                    changeUser(scope.row, optionsUser, scope.row.roleCode)
                  "
                  v-model="scope.row.roleCode"
                  placeholder="请选择角色"
                >
                  <c-option
                    v-for="item in optionsUser"
                    :disabled="item.disabled"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </c-option>
                </c-select>
              </template>
            </template>
          </c-table-column>
          <c-table-column prop="consultLevel" label="协同程度">
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">{{
                arrFind(optionsLevel, scope.row.joinMethodCode) || '--'
              }}</template>
              <template v-else>
                <!-- 此处为普通下拉选择 -->
                <c-select
                  :class="{
                    err: !scope.row.joinMethodCode && scope.row.isValidate
                  }"
                  @change="
                    changeLevel(
                      scope.row,
                      optionsLevel,
                      scope.row.joinMethodCode
                    )
                  "
                  v-model="scope.row.joinMethodCode"
                  placeholder="请选择协同程度"
                >
                  <c-option
                    v-for="item in optionsLevel"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </c-option>
                </c-select>
              </template>
            </template>
          </c-table-column>
          <c-table-column
            prop="descriptions"
            label="处置要求"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">
                <div v-if="scope.row.descriptions.length < 135">
                  {{ scope.row.descriptions }}
                </div>
                <c-tooltip
                  v-else
                  effect="dark"
                  :content="scope.row.descriptions"
                  placement="top"
                >
                  <div
                    style="
                      width: 100%;
                      padding: 0px;
                      display: -webkit-box;
                      -webkit-line-clamp: 5;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      -webkit-box-orient: vertical;
                      white-space: normal;
                      line-height: 18px;
                    "
                  >
                    {{ scope.row.descriptions }}
                  </div>
                </c-tooltip>
              </template>
              <template v-else>
                <!-- 此处为普通输入框 -->
                <c-input
                  :class="{
                    err: !scope.row.descriptions && scope.row.isValidate
                  }"
                  v-model="scope.row.descriptions"
                  placeholder="请填写处置要求"
                ></c-input>
              </template>
            </template>
          </c-table-column>
          <c-table-column prop="timeLimit" label="处置时限" width="200">
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">{{
                scope.row.limitTime
                  ? `${scope.row.limitTime}${scope.row.limitTimeLabel}`
                  : '--'
              }}</template>
              <template v-else>
                <c-input
                  :class="{
                    err: !scope.row.limitTime && scope.row.isValidate
                  }"
                  @input="
                    (val) => {
                      scope.row.limitTime = changeTime(val)
                    }
                  "
                  :disabled="scope.row.disableLimitTime"
                  v-model="scope.row.limitTime"
                  placeholder="请填写时限"
                >
                  <c-select
                    style="width: 75px"
                    slot="append"
                    :disabled="scope.row.disableLimitTime"
                    :class="{
                      err: !scope.row.limitTimeUnit && scope.row.isValidate
                    }"
                    v-model="scope.row.limitTimeUnit"
                    placeholder="请选择时限部门"
                  >
                    <c-option
                      v-for="item in optionsTime"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </c-option>
                  </c-select>
                </c-input>
              </template>
            </template>
          </c-table-column>
          <c-table-column
            prop="examineDesc"
            label="审核意见"
            v-if="mode !== 'edit'"
          >
          </c-table-column>
          <c-table-column prop="btns" label="操作" v-if="mode === 'edit'">
            <template slot-scope="scope">
              <c-button
                type="text"
                size="mini"
                @click="handleEdit(scope.row, 'rule')"
              >
                {{ scope.row.editable ? '确定' : '修改' }}
              </c-button>
              <c-button
                size="mini"
                type="text"
                @click="handleDelete(detail.itemRulesDTOList, scope.$index)"
                >删除</c-button
              >
            </template>
          </c-table-column>
        </c-table>
        <p
          v-if="addtype !== 'record' && detail.itemFileDTOList.length"
          class="flex-align"
        >
          相关材料
        </p>
        <div style="display: flex" v-if="addtype !== 'record'">
          <FileView :files="detail.itemFileDTOList" v-if="mode !== 'edit'" />
          <c-upload
            v-else
            class="upload-demo"
            action="/api/sys/file/upload"
            :on-preview="handlePreview"
            :on-error="handleError"
            :on-remove="
              (file, files) => {
                handleRemove(file, files, detail, 'itemFileDTOList')
              }
            "
            accept=".png,.jpg,.doc,.docx,.pdf"
            :on-success="
              (res, file, fileList) => {
                this.$set(detail, 'itemFileDTOList', fileList)
              }
            "
            multiple
            :before-upload="fileJudge1"
            :limit="5"
            :on-exceed="handleExceed"
            :file-list="detail.itemFileDTOList"
          >
            <c-button class="upload-btn" size="small" type="primary"
              >点击上传</c-button
            >
          </c-upload>
        </div>
        <div
          class="flex-align"
          v-if="
            (addtype !== 'rule' &&
              mode === 'edit' &&
              !detail.itemCoordinateRecordDTOList.length) ||
            (addtype !== 'rule' && detail.itemCoordinateRecordDTOList.length)
          "
        >
          <p class="title">协调记录</p>
          <div
            class="add-row"
            @click="dealArray(detail.itemCoordinateRecordDTOList)"
            v-if="mode === 'edit' && addtype !== 'rule'"
          >
            + 添加协调记录
          </div>
        </div>
        <c-table
          v-if="
            (addtype !== 'rule' &&
              mode === 'edit' &&
              !detail.itemCoordinateRecordDTOList.length) ||
            (addtype !== 'rule' && detail.itemCoordinateRecordDTOList.length)
          "
          :data="detail.itemCoordinateRecordDTOList || []"
          style="width: 100%"
          @mousewheel.native="scroll"
          ref="scroll-table"
        >
          <c-table-column prop="dept" label="参与部门" min-width="160">
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">{{
                scope.row.unitName
              }}</template>
              <template v-else>
                <c-cascader
                  filterable
                  :show-all-levels="false"
                  placeholder="请选择参与部门"
                  :options="deptTreeData"
                  :props="partInTreeProps"
                  v-model="scope.row.unitCode"
                  @change="
                    (val) =>
                      handleTreeSelectChange(scope.row, val, 'unitName', true)
                  "
                >
                </c-cascader>
                <!-- 猜测此处为树形选择 -->
                <!-- <c-select @change="changeCode(scope.row, optionsDept, scope.row.unitCode, 'unitName')" v-model="scope.row.unitCode" multiple placeholder="请选择协同部门">
                  <c-option
                    v-for="item in optionsDept"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </c-option>
                </c-select> -->
              </template>
            </template>
          </c-table-column>
          <c-table-column prop="consultTime" label="协调时间" min-width="230">
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">{{
                scope.row.coordinateTime
              }}</template>
              <template v-else>
                <TimeSel v-model="scope.row.coordinateTime" />
              </template>
            </template>
          </c-table-column>
          <c-table-column
            prop="coordinateAddr"
            label="协调地址"
            min-width="160"
          >
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">{{
                scope.row.coordinateAddr
              }}</template>
              <template v-else>
                <!-- 猜测此处为普通输入框 -->
                <c-input
                  type="textarea"
                  rows="3"
                  v-model="scope.row.coordinateAddr"
                ></c-input>
              </template>
            </template>
          </c-table-column>
          <c-table-column
            prop="coordinateResult"
            label="协调结果"
            min-width="160"
          >
            <template slot-scope="scope">
              <template v-if="!scope.row.editable">
                <div v-if="scope.row.coordinateResult.length < 75">
                  {{ scope.row.coordinateResult }}
                </div>
                <c-tooltip
                  v-else
                  effect="dark"
                  :content="scope.row.coordinateResult"
                  placement="top"
                >
                  <div
                    style="
                      width: 100%;
                      padding: 0px;
                      display: -webkit-box;
                      -webkit-line-clamp: 5;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      -webkit-box-orient: vertical;
                      white-space: normal;
                      line-height: 18px;
                    "
                  >
                    {{ scope.row.coordinateResult }}
                  </div>
                </c-tooltip>
              </template>
              <template v-else>
                <!-- 猜测此处为普通输入框 -->
                <c-input
                  type="textarea"
                  rows="3"
                  v-model="scope.row.coordinateResult"
                ></c-input>
              </template>
            </template>
          </c-table-column>
          <c-table-column prop="files" label="附件" min-width="160">
            <template slot-scope="scope">
              <FileView
                v-if="!scope.row.editable"
                :files="scope.row.itemCoordinateRecordFileList"
              />
              <c-upload
                v-else
                class="upload-demo"
                :on-success="
                  (res, file, fileList) => {
                    $set(scope.row, 'itemCoordinateRecordFileList', fileList)
                  }
                "
                accept=".png,.jpg,.doc,.docx,.pdf,.mp4"
                action="/api/sys/file/upload"
                :on-preview="handlePreview"
                :on-error="handleError"
                :on-remove="
                  (file, files) => {
                    handleRemove(
                      file,
                      files,
                      scope.row,
                      'itemCoordinateRecordFileList'
                    )
                  }
                "
                :before-upload="fileJudge"
                multiple
                :limit="5"
                :on-exceed="handleExceed"
                :file-list="scope.row.itemCoordinateRecordFileList || []"
              >
                <c-button size="small" type="primary">点击上传</c-button>
              </c-upload>
            </template>
          </c-table-column>
          <c-table-column
            prop="btns"
            label="操作"
            v-if="mode === 'edit'"
            width="80px;"
            align="center"
            header-align="center"
          >
            <template slot-scope="scope">
              <c-button
                size="mini"
                type="text"
                style="margin: 0 0 5px 0"
                @click="handleEdit(scope.row, 'record')"
              >
                {{ scope.row.editable ? '确定' : '修改' }}
              </c-button>
              <c-button
                style="margin: 0"
                size="mini"
                type="text"
                @click="
                  handleDelete(detail.itemCoordinateRecordDTOList, scope.$index)
                "
                >删除</c-button
              >
            </template>
          </c-table-column>
        </c-table>
      </template>
    </div>
  </detail>
</template>
<script>
import FileView from '@/component/ConsultResult/src/FileView/index.js'
import { parseTime, deepClone, treeFindPath } from '@/utils/index.js'
import { getCheckDetail } from '@/api/check.js'
import { getDictByType, getDeptmentListAll } from '@/api/config_platform.js'
import { getAllDeptment } from '@/api/preview.js'
import { mapGetters } from 'vuex'
import _ from 'lodash'

const TimeSel = {
  name: 'TimeSel',
  props: {
    value: {
      // type: String,
      default: function () {
        var date = new Date()
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var strDate = date.getDate()
        if (month >= 1 && month <= 9) {
          month = '0' + month
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = '0' + strDate
        }
        var currentdate = `${year}-${month}-${strDate} 00:00-23:59`
        return currentdate
      }
    }
  },
  data () {
    return {
      date: '',
      timerange: ''
    }
  },
  watch: {
    value (time) {
      this.refTime(time)
    }
  },
  mounted () {
    this.refTime(this.value)
    this.$emit('input', `${this.date} ${this.getTimeRange(this.timerange)}`)
  },
  methods: {
    refTime (time) {
      const [date, times] = time.split(' ')
      this.timerange = times.split('-').map((i) => new Date(`${date} ${i}`))
      this.date = date
    },
    change () {
      this.$emit('input', `${this.date} ${this.getTimeRange(this.timerange)}`)
    },
    getTimeRange ([start, end]) {
      const startTime = parseTime(start, 'h:i')
      const endTime = parseTime(end, 'h:i')
      return `${startTime}-${endTime}`
    }
  },
  render () {
    return (
      <div>
        <div class="time-sel-column">
          <label>日期</label>
          <c-date-picker
            on-change={this.change}
            type="date"
            clearable={false}
            value-format="yyyy-MM-dd"
            v-model={this.date}
            placeholder="选择日期"
          ></c-date-picker>
        </div>
        <div class="time-sel-column">
          <label>时间</label>
          <c-time-picker
            on-change={this.change}
            is-range
            v-model={this.timerange}
            range-separator="至"
            clearable={false}
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            placeholder="选择时间范围"
          ></c-time-picker>
        </div>
      </div>
    )
  }
}
function treeToList (treeData, list) {
  if (!Array.isArray(treeData)) {
    return
  }
  treeData.forEach((item) => {
    const { id, parentId, text, deptCode } = item
    list.push({ id, parentId, text, deptCode })
    treeToList(item.childNode, list)
  })
}
export default {
  name: 'ConsultResult',
  components: {
    FileView,
    TimeSel
  },
  computed: {
    ...mapGetters(['user'])
  },
  props: {
    mode: {
      type: String,
      default: 'detail'
    },
    addtype: {
      type: String,
      default: ''
    },
    originData: {
      type: Object,
      default () {
        return null
      }
    }
  },
  watch: {
    originData: {
      handler () {
        this.originData && this.handData(deepClone(this.originData))
      },
      deep: true
    }
  },
  mounted () {
    this.init()
  },
  data () {
    return {
      scrollEl: null,
      deptTreeData: [], // 部门树数据
      deptListData: [], // 部门扁平数据
      treeProps: {
        label: 'text',
        value: 'deptCode',
        children: 'childNode',
        checkStrictly: true,
        expandTrigger: 'hover',
        emitPath: false
      },
      partInTreeProps: {
        label: 'text',
        value: 'deptCode',
        children: 'childNode',
        checkStrictly: true,
        expandTrigger: 'hover',
        multiple: true,
        emitPath: false
      },
      detail: this.getDefaultDetail(),
      optionsLevel: [],
      optionsUser: [],
      optionsDept: [],
      optionsTime: [],
      pickerOptions: {
        disabledDate () {
          return false
        }
      },
      needInitUnitCode: false // 需要初始化
    }
  },
  methods: {
    init () {
      const id = this.$route.query.id
      if (id) {
        getCheckDetail({ id }).then(({ success, data }) => {
          if (success) {
            this.handData(data)
          }
        })
      }

      // 获取部门信息
      // getDeptmentListAll().then(({ success, data }) => {
      const { pid, deptId } = this.user
      const params = {
        groupId: 1, // 全部 this.user.groupId
        node: pid
      }
      getAllDeptment(params).then(({ success, data }) => {
        if (success) {
          this.deptTreeData = data
          // tree转list
          treeToList(data, this.deptListData)
          if (this.needInitUnitCode) {
            this.detail.itemCoordinateRecordDTOList.forEach((item) => {
              item.unitCode = item.unitCode.map((id) => {
                return treeFindPath(this.deptTreeData, (item) => item.id === id)
              })
            })
          }
          // this.dealDept() // 重复部门处理
        }
      })
      this.seTDict(getDictByType('RULES_LEVEL'), 'optionsLevel', () => {
        this.dealLevel()
      }) // 协同程度
      this.seTDict(getDictByType('RULES_ROLE'), 'optionsUser', () => {
        this.dealUser() // 牵头部门存在处理
      }) // 协同角色
      this.seTDict(getDictByType('DISPOSAL_TIME_LIMIT'), 'optionsTime') // 协同角色
    },
    handData (data) {
      data.itemCoordinateRecordDTOList =
        data.itemCoordinateRecordDTOList?.map((item) => {
          // 处理参与部门 // compact 用来去除假值
          item.unitCode = _.compact(item.unitCode.split(','))

          // 处理附件
          item.itemCoordinateRecordFileList =
            item.itemCoordinateRecordFileList.map((file) => {
              return {
                url: file.fileUrl,
                name: file.fileName,
                id: file.id
              }
            })
          return item
        }) || []
      data.itemRulesDTOList =
        data.itemRulesDTOList?.map((item) => {
          item.isValidate = false
          return item
        }) || []
      data.itemFileDTOList =
        data.itemFileDTOList?.map((file) => {
          return {
            url: file.fileUrl,
            name: file.fileName,
            id: file.id
          }
        }) || []
      this.detail = data
    },
    getDefaultDetail () {
      return {
        itemCoordinateRecordDTOList: [],
        itemFileDTOList: [],
        itemRulesDTOList: []
      }
    },
    reset () {
      this.detail = this.getDefaultDetail()
    },
    scroll (event) {
      if (!this.scrollEl) {
        const els = this.$refs['scroll-table'].$el.getElementsByClassName(
          'el-table__body-wrapper'
        )
        if (els.length) {
          this.scrollEl = els[0]
        }
      }
      var delta = 0
      // For IE.
      if (!event) {
        event = this.__window__.event
      }
      // IE/Opera.
      if (event.wheelDelta) {
        delta = event.wheelDelta / 120
      } else if (event.detail) {
        // Mozilla case.
        /** In Mozilla, sign of delta is different than in IE.
         * Also, delta is multiple of 3.
         */
        delta = -event.detail / 3
      }
      /** If delta is nonzero, handle it.
       * Basically, delta is now positive if wheel was scrolled up,
       * and negative, if wheel was scrolled down.
       */
      if (delta) {
        this.handlewheel(delta, event)
      }
      /** Prevent default actions caused by mouse wheel.
       * That might be ugly, but we handle scrolls somehow
       * anyway, so don't bother here..
       */
      // if (event.preventDefault) {
      //   event.preventDefault()
      // }
      // event.returnValue = false
      // return false
    },
    /**
     * @description 处理树形结构选择 label回显
     * @param { object } row 当前行数据
     * @param {array} val 当前选中值
     * @param {string} filed 回显的字段名称
     * @param {boolean} multiple 是否是多选  默认否
     */
    handleTreeSelectChange (row, val, filed, multiple = false) {
      if (!val) return
      if (multiple) {
        // 多选模式 改为一维数组
        const targetCodes = val
        const labelArr = []
        targetCodes.map((deptCode) => {
          const target = this.deptListData.find(
            (item) => item.deptCode === deptCode
          )
          if (target) {
            labelArr.push(target.text)
          }
        })
        this.$set(row, filed, labelArr.join())
      } else {
        // 单选模式 基本数据类型
        const deptCode = val
        const target = this.deptListData.find(
          (item) => item.deptCode === deptCode
        )
        if (target) {
          this.$set(row, filed, target.text)
        }
      }
    },
    handlewheel (delta, event) {
      const { scrollWidth, offsetWidth, scrollLeft } = this.scrollEl
      if (
        (scrollLeft === 0 && delta > 0) ||
        (scrollLeft === scrollWidth - offsetWidth && delta < 0)
      ) {
        // 冒泡
      } else {
        this.scrollEl.scrollLeft = scrollLeft + delta * -1 * 50
        if (event.preventDefault) {
          event.preventDefault()
        }
        event.returnValue = false
      }
    },
    changeLevel (row, codes, code) {
      this.dealLevel()
      this.changeCode(row, codes, code, 'joinMethodName')
    },
    dealLevel () {
      // 仅通知时无需设置时间
      this.detail.itemRulesDTOList.forEach((i) => {
        if (i.joinMethodCode === '2') {
          i.disableLimitTime = true
          i.limitTime = ''
          i.limitTimeUnit = '1'
        } else {
          i.disableLimitTime = false
        }
      })
    },
    changeUser (row, codes, code) {
      this.dealUser()
      this.changeCode(row, codes, code, 'roleName')
    },
    dealUser () {
      // 当存在牵头部门时，将不能选择牵头部门
      const ifMainUser = !!this.detail.itemRulesDTOList.filter(
        (i) => i.roleCode === '1'
      )?.length
      const el = this.optionsUser.findIndex((i) => i.codeValue === '1')
      if (el !== -1) {
        this.$set(this.optionsUser[el], 'disabled', ifMainUser)
      }
    },
    validateRule () {
      let ifErr = false
      this.detail.itemRulesDTOList.forEach((rule) => {
        rule.isValidate = true
        if (ifErr) return
        const err =
          !rule.roleCode ||
          !rule.unitCode ||
          !rule.joinMethodCode ||
          !rule.descriptions ||
          (rule.joinMethodCode !== '2' && !rule.limitTimeUnit)
        if (err) {
          ifErr = true
        }
      })
      return !ifErr
    },
    validateMain (data) {
      // if (!data.itemRulesList.find((i) => i.roleCode === '1')) {
      //   this.$message.error('必须有牵头部门')
      //   return false
      // }
      /* 需求调整 材料可以不必填
      if (!data.itemFileList.length) {
        this.$message.error('请上传相关材料')
        return false
      } */
      // 协同规则协同部门
      const ruleUnitCodeList = data.itemRulesList.map((item) => item.unitCode)
      // 去重后比较
      if (ruleUnitCodeList > [...new Set(ruleUnitCodeList)]) {
        this.$message.error('协同部门不能重复')
        return false
      }
      /* 需求调整，不同协调记录 协同部门可以重复
       // 协同记录参与部门
      const recordUnitCodeList = data.itemCoordinateRecordList.map(
        (item) => item.unitCode
      )
      // 去重后比较
      if (recordUnitCodeList > [...new Set(recordUnitCodeList)]) {
        this.$message.error('参与部门不能重复')
        return false
      } */
      return true
    },
    submit () {
      const data = this.getVal()
      if (this.addtype !== 'record') {
        if (this.validateRule() && this.validateMain(data)) {
          return data
        }
      } else {
        return data
      }
    },
    getVal () {
      const { itemCoordinateRecordDTOList, itemFileDTOList, itemRulesDTOList } =
        this.detail
      const index = itemCoordinateRecordDTOList.findIndex((el) => {
        return el.unitCode === undefined || el.unitCode.length === 0
      })
      if (index !== -1) {
        this.$message({
          type: 'error',
          message: '参与部门不能为空',
          customClass: 'mz-index'
        })
      } else {
        return {
          itemCoordinateRecordList: deepClone(itemCoordinateRecordDTOList).map(
            (item) => {
              item.unitCode = item.unitCode.join(',')
              item.itemCoordinateRecordFileList = (
                item.itemCoordinateRecordFileList || []
              ).map((file) => {
                return {
                  id: file.id,
                  fileName: file.name,
                  fileUrl: file.response?.data?.url || file.url || ''
                }
              })
              return item
            }
          ),
          itemFileList: itemFileDTOList.map((file) => {
            return {
              id: file.id,
              fileName: file.name,
              fileUrl: file.response?.data?.url || file.url || ''
            }
          }),
          itemRulesList: deepClone(itemRulesDTOList).map((item) => {
            item.examineCode = null // 默认不带有审核意见
            item.examineDesc = null // 默认不带有审核意见
            item.examineName = null // 默认不带有审核意见

            return item
          })
        }
      }
    },
    dealArray (arr) {
      if (arr instanceof Array) {
        arr.push({ editable: true, isValidate: false, limitTimeUnit: '1' })
      } else {
        arr = [{ editable: true, isValidate: false, limitTimeUnit: '1' }]
      }
    },
    seTDict (funcPromise, dataname, callback = () => { }) {
      funcPromise.then(({ success, data }) => {
        this[dataname] = (success ? data || [] : []).map((i) => {
          i.value = i.codeValue
          i.label = i.codeName
          return i
        })
        if (dataname === 'optionsTime') {
          const ind = this[dataname].findIndex((el) => {
            return el.codeValue === '3'
          })
          if (ind !== -1) {
            this[dataname].splice(ind, 1)
          }
        }
        callback()
      })
    },
    handleEdit (row, type) {
      if (type === 'record') {
        if (!row.unitCode || row.unitCode.length === 0) {
          this.$message({
            type: 'error',
            message: '参与部门不能为空',
            customClass: 'mz-index'
          })
          return
        }
      }
      // 可编辑状态验证必填
      if (row.editable) {
        // 协同规则，必填验证
        if (type === 'rule') {
          const ifErr =
            !row.roleCode ||
            !row.unitCode ||
            !row.joinMethodCode ||
            !row.descriptions ||
            (row.joinMethodCode !== '2' && !row.limitTimeUnit)
          if (ifErr) {
            row.isValidate = true
            return
          }
        }
      }
      this.$set(row, 'editable', !row.editable)
      const limitTimeLabel = this.getLimitTimeLabel(row.limitTimeUnit)
      this.$set(row, 'limitTimeLabel', limitTimeLabel)
    },
    // 设置unitName
    changeCode (row, codes, code, codeName) {
      this.$set(row, codeName, this.arrFind(codes, code))
    },
    /**
     * 获取事件列表
     */
    getLimitTimeLabel (value) {
      if (!value) return ''
      const target = this.optionsTime.find((item) => item.value === value)
      return target?.label
    },
    dealDept () {
      this.optionsDept.forEach((item) => {
        const el = this.detail.itemRulesDTOList.find(
          (i) => i.unitCode === item.value
        )
        item.disabled = !!el
      })
    },
    changeDept (row, codes, code) {
      // 不能重复选择部门
      this.dealDept()
      this.changeCode(row, codes, code, 'unitName')
    },
    arrFind (arr, value) {
      if (value instanceof Array) {
        return value
          .map((val) => {
            return arr.find((i) => i.value + '' === val + '')?.label || ''
          })
          .join('，')
      } else if (typeof value === 'string' || typeof value === 'number') {
        return arr.find((i) => i.value + '' === value + '')?.label || ''
      } else {
        return ''
      }
    },
    handleDelete (data, index) {
      // this.$confirm('确定删除这条信息？').then(() => {
      //   data.splice(index, 1)
      //   this.$message.success('删除成功')
      // })
      data.splice(index, 1)
      this.$message.success('删除成功')
      // 删除后更新牵头部门唯一性
      this.dealUser()
    },
    handleRemove (file, fileList, source, name) {
      this.$set(source, name, fileList)
    },
    handlePreview (file) {
      const xhr = new XMLHttpRequest()
      const url = file.url || file.response.data.url
      const fileName = file.name || url.split('/').pop()
      xhr.open('get', url)
      xhr.responseType = 'blob'
      xhr.send()
      xhr.onload = function (sues) {
        const data = xhr.response
        const imgurl = URL.createObjectURL(data)
        let a = document.createElement('a')
        a.href = imgurl
        a.download = fileName || ''
        a.click()
        a = null
      }
    },
    handleExceed (files, fileList) {
      this.$message.warning('最多可上传5个文件，已超过限制')
    },
    fileJudge (file) {
      if (file && file.size / 1024 / 1204 > 100) {
        this.$message.warning('上传文件超过最大限制 100 M')
        return false
      }
    },
    fileJudge1 (file) {
      if (file && file.size / 1024 / 1204 > 10) {
        this.$message.warning('上传文件超过最大限制 10 M')
        return false
      }
    },
    handleError () {
      this.$message.warning('文件上传失败')
    },
    // 输入时间
    changeTime (val) {
      // const MaxNumber = 99;
      let pval = ''
      pval = val.replace(/^\./g, '') // 必须保证第一个为数字而不是.
      pval = pval.replace(/[^\d.]/g, '')
      pval = pval.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      pval = pval.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') // 不能重复出现点
      pval = pval.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3') // 只能输入1个小数
      const len1 = pval.substr(0, 1)
      const len2 = pval.substr(1, 1)
      // 如果第一位是0，第二位不是点，就用数字把点替换掉
      if (pval.length > 1 && len1 === '0' && len2 !== '.') {
        pval = pval.substr(1)
      }
      // let n = pval.indexOf(".");
      // if (n !== -1 && pval.split(".")[0] == MaxNumber) {
      //   pval = MaxNumber;
      // }
      // if (pval > MaxNumber) {
      //   pval = pval.slice(0, -1);
      // }
      return pval
    }
    // beforeRemove (file) {
    //   return this.$confirm(`确定移除 ${file.name}？`)
    // }
  }
}
</script>
<style lang="scss">
.ConsultResult {
  .flex-align {
    margin: 22px 0 10px 0;
  }
  .title {
    font-family: PingFangSC-Medium;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
    font-weight: bold;
  }
  .err input {
    border-color: red;
  }
  .el-select {
    width: 100%;
  }
  p {
    // color: #333333;
    // line-height: 22px;
    // padding: 10px 0;
  }
  .upload-info {
    color: #999999;
    margin-left: 5px;
  }
  .upload-btn {
    margin-top: 10px;
  }
  .time-sel-column {
    display: flex;
    width: 100%;
    margin-bottom: 5px;
    > div {
      flex: 1;
    }
    > label {
      margin-right: 10px;
      line-height: 32px;
    }
  }
  .el-date-editor .el-range-separator {
    line-height: 24px !important;
  }
  .add-row {
    margin-left: 15px;
    cursor: pointer;
    // width: 100%;
    height: 48px;
    line-height: 48px;
    font-size: 14px;
    color: $--color-primary;
    // border-bottom: 1px solid #e6e6e6;
    // text-align: center;
    &:hover {
      // background: rgba($--color-primary, 0.06);
    }
  }
  .el-table {
    * {
      &::-webkit-scrollbar {
        display: block;
        height: 8px;
        width: 8px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.3);
        border-radius: 4px;
      }
    }
  }
}
</style>
